package net.codeyouth.codegen.util

import org.apache.velocity.app.Velocity
import org.apache.velocity.runtime.RuntimeConstants
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader

/**
 * @author Frank create on 16/2/23 15:19
 */
class VelocityUtil {

    private static final ThreadLocal<Velocity> VELOCITY_HOLDER = new ThreadLocal<>()

    /**
     * 获取唯一的Velocity对象.
     *
     * @return Velocity对象
     */
    static Velocity getSimpleEngine() {
        Velocity velocity = VELOCITY_HOLDER.get()
        try {
            if (velocity == null) {
                velocity = new Velocity()
                velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "class")
                velocity.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.name)
                velocity.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8")
                velocity.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8")
            }
        } catch (Exception e) {
            e.printStackTrace()
        } finally {
            VELOCITY_HOLDER.set(velocity)
        }
        return velocity
    }

}
